import request from '@/common/request.js'

export const imageFormats = [
	'JPEG',
	'JPG',
	'PNG',
	'GIF'
];
export const exts = ['doc', ' xls', 'ppt', 'pdf', 'docx', 'xlsx', 'pptx'];
export function downloadFile(info = {
	url,
	success,
	error
}) {
	let {
		url,
		success,
		error
	} = info;
	uni.showLoading();
	uni.downloadFile({ // downloadFile的url必须为http或者https
		url: url,
		success(res) {
			if (res.statusCode === 200) {
				const tempFilePath = res.tempFilePath
				const fileExt = getFileExt(tempFilePath)
				if (imageFormats.includes(fileExt.ext.toUpperCase())) {
					uni.saveImageToPhotosAlbum({
						filePath: tempFilePath,
						success: () => {
							//提示保存成功
							uni.showToast({
								title: '保存成功',
								duration: 1000,
							})
							if (success) {
								success()
							}
						},
						fail: (res) => {
							//失败关闭提示信息！！！
							uni.showToast({
								icon: 'none',
								title: '下载失败',
								duration: 1000,
							})
							if (error) {
								error()
							}
							console.log("下载失败", res);
						},
						complete: function() {
							//隐藏提示
						}
					})
				} else {
					uni.saveFile({
						tempFilePath: res.tempFilePath,
						success: (data) => {
							console.log('data', data)
							var savedFilePath = data.savedFilePath;
							uni.showToast({
								title: '保存成功',
								duration: 1000,
							})
							if (success) {
								success()
							}
							if (exts.includes(fileExt.ext.toLowerCase())) {
								uni.openDocument({
									filePath: savedFilePath
								})
							}
						},
						fail: (res) => {
							//失败关闭提示信息！！！
							uni.showToast({
								icon: 'none',
								title: '下载失败',
								duration: 1000,
							})
							console.log("下载失败", res);
							if (error) {
								error()
							}
						},
						complete: function() {}
					})
				}
			}
		},
		fail(err) {
			console.log('downloadfile err', err)
		}
	})
	uni.hideLoading();
}

/**
 * 获取文件名和后缀
 * @param {Object} name
 */
export function getFileExt(name) {
	const last_len = name.lastIndexOf('.')
	const len = name.length
	return {
		name: name.substring(0, last_len),
		ext: name.substring(last_len + 1, len)
	}
}


export function formatRichText(html) {
	let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
		return match;
	});
	newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
		match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi,
			'max-width:100%;');
		return match;
	});
	newContent = newContent.replace(/<br[^>]*\/>/gi, '');
	newContent = newContent.replace(/\<img/gi,
		'<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"');
	return newContent;
}

//获取之前页面的信息
export function getBeforePage(num = 1) {
	let pages = getCurrentPages(); // 当前页面
	let beforePage = pages[pages.length - (num + 1)]; // 前一个页面
	return beforePage;
}
//字符串转为大驼峰
export function camelCase(str) {
	return str.replace(/_([a-z])/g, (fullMatch, g1, index) => {
		if (index === 0) return g1;
		return g1.toUpperCase();
	});
}


export function goBack(param = {
	title: "提交成功"
}) {

	param.title ?? "提交成功"
	uni.showToast({
		title: param.title,
		duration: 3000,
		success() {
			let beforePage =
				getBeforePage();
			if (beforePage) {
				beforePage.$vm.init();
			}
			setTimeout(() => {
				uni.navigateBack({
					delta: 1
				});
			}, 1000)
		}
	})
}


export function getCustomBar() {
	uni.getSystemInfo({
		success: function(e) {
			// #ifndef MP
			Vue.prototype.StatusBar = e.statusBarHeight;
			if (e.platform == 'android') {
				Vue.prototype.CustomBar = e.statusBarHeight + 50;
			} else {
				Vue.prototype.CustomBar = e.statusBarHeight + 45;
			};
			// #endif

			// #ifdef MP-WEIXIN
			Vue.prototype.StatusBar = e.statusBarHeight;
			let custom = wx.getMenuButtonBoundingClientRect();
			Vue.prototype.Custom = custom;
			Vue.prototype.CustomBar = custom.bottom + custom.top - e.statusBarHeight + 4;
			// #endif		

			// #ifdef MP-ALIPAY
			Vue.prototype.StatusBar = e.statusBarHeight;
			Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight;
			// #endif
		}
	});

}

/**
 * 根据身份证号码获取信息
 * @param {string} idCard - 身份证号码 
 * @returns {object} 返回包含解析结果的对象
 */
export function parseIdCard(idCard) {
	const provinces = [
		'北京市',
		'天津市',
		'河北省',
		'山西省',
		'内蒙古自治区',
		'辽宁省',
		'吉林省',
		'黑龙江省',
		'上海市',
		'江苏省',
		'浙江省',
		'安徽省',
		'福建省',
		'江西省',
		'山东省',
		'河南省',
		'湖北省',
		'湖南省',
		'广东省',
		'广西壮族自治区',
		'海南省',
		'重庆市',
		'四川省',
		'贵州省',
		'云南省',
		'西藏自治区',
		'陕西省',
		'甘肃省',
		'青海省',
		'宁夏回族自治区',
		'新疆维吾尔自治区',
		'台湾省',
		'香港特别行政区',
		'澳门特别行政区'
	]
	let result = {}
	const regex = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})(\d|X|x)$/
	const match = idCard.match(regex)
	if (match) {
		const provinceCode = parseInt(match[1].substring(0, 2))
		result.province = provinces[provinceCode - 1] || ''
		result.city = match[1].substring(2, 4) || ''
		result.area = match[1].substring(4, 6) || ''
		const year = parseInt(match[2])
		const month = parseInt(match[3], 10)
		const day = parseInt(match[4], 10)
		result.birthday = new Date(year, month - 1, day)
		result.gender = match[5] % 2 === 0 ? '2' : '1'
		result.checkDigit = match[6] || ''


		// 计算当前时间
		var currentDate = new Date();
		var currentYear = currentDate.getFullYear();
		var currentMonth = currentDate.getMonth() + 1;
		var currentDay = currentDate.getDate();

		// 计算年龄
		var age = currentYear - parseInt(year);

		if (currentMonth < parseInt(month) || (currentMonth === parseInt(month) && currentDay < parseInt(day))) {
			age--;
		}
		result.age = age
	}
	return result
}


/**
 * 域名替换
 * @param {string} oldUrl - url 
 * @param {string} newDomain - 域名 
 * 
 * @returns {object} 返回包含解析结果的对象
 */
export function domainReplace(oldUrl, newDomain) {
	if (!oldUrl) {
		return ""
	}
	const regex = /^https?:\/\/(?<domain>[^/]+)/i;
	return oldUrl.replace(regex, `${newDomain}`);
}


export function urlReplaceDomain(url) {
	return url.replace(request.zhengwuwaiDomain, request.qianzhijiDomain);
}

export function urlReplaceDomainOpposite(url) {
	return url.replace(request.qianzhijiDomain, request.zhengwuwaiDomain);

}

/**
 * 数组分包
 */
export function arrayChunk(array, chunkSize = 10) {
	const chunkedArray = [];
	while (array.length) {
		chunkedArray.push(array.splice(0, chunkSize));
	}
	return chunkedArray;
}


export function isFormFilled(data) {
	for (const key in data) {
		const value = data[key];
		if (!((Array.isArray(value) && value.length === 0) || (typeof value === 'object' && Object.keys(value)
				.length === 0)) && value) {
			return true;
		}
	}
	return false
}


export function checkPermission(title) {//title，权限未开启提示的消息
    return new Promise((resolve) => {
        plus.android.requestPermissions(
            ["android.permission.CALL_PHONE", "android.permission.READ_PHONE_STATE"],//这里面放需要的权限,我这边主要是打电话以及通讯录的一些操作权限
            function (resultObj) {
				console.log('resultObj',resultObj);
                if (resultObj.granted.length < 4) { //resultObj.granted是授权的权限，是一个数组，你可以直接判断长度也可以拿出来单独判断
                  uni.showToast({
                        icon: "none",
                        title,
                    });
                    resolve(false)
                    let timer1 = setTimeout(() => { //没有开对应的权限，打开app的系统权限管理页
                        var Intent = plus.android.importClass("android.content.Intent");
                        var Settings = plus.android.importClass("android.provider.Settings");
                        var Uri = plus.android.importClass("android.net.Uri");
                        var mainActivity = plus.android.runtimeMainActivity();
                        var intent = new Intent();
                        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
                        intent.setData(uri);
                        mainActivity.startActivity(intent);
                        clearTimeout(timer1)
                        timer1 = null
                    }, 1000)
                } else {
					if(resultObj.deniedAlways.length == 0){
						resolve(true)
					}
                }
            }
        );
    })
}


export function checkContect(){
	return new Promise((resolve, reject) => {
		permission.requestAndroidPermission('android.permission.READ_CALL_LOG').then(res => {
			if(res==1){
				resolve();
			}else if(res == 0){
				uni.showModal({
					title: '提示',
					content: '被永久拒绝授权, 请打开拨打电话权限',
					success() {
						permission.gotoAppPermissionSetting();
					}
				});
				reject();
			}else if(res == -1){
				uni.showModal({
					title: '提示',
					content: '未获取授权, 请打开拨打电话权限',
					success() {
						permission.gotoAppPermissionSetting();
					}
				});
				reject();
			}
		}).catch(() => {
			uni.showModal({
				title: '提示',
				content: '请打开拨打电话权限',
				success() {
					permission.gotoAppPermissionSetting();
				}
			});
			reject();
		});
	});
}

export function deepClonesss(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

export function deepClone(source) {
  if (source === null || typeof source !== 'object') return source;
  
  // 处理数组
  if (Array.isArray(source)) {
    return source.map(item => deepClone(item));
  }
  
  // 处理日期
  if (source instanceof Date) {
    return new Date(source.getTime());
  }
  
  // 处理普通对象
  const clone = {};
  for (const key in source) {
    if (source.hasOwnProperty(key)) {
      clone[key] = deepClone(source[key]);
    }
  }
  return clone;
}

